/* eslint-disable @typescript-eslint/no-use-before-define */
import { PageContainer } from '@ant-design/pro-layout';
import { Button, Cascader, Divider, message, Modal, Popconfirm, Tag } from 'antd';
import { useEffect, useReducer, useRef, useState } from 'react';
import Add from './mainContent/add';
import Update from './mainContent/update';
import Detail from './mainContent/detail';
import { ExclamationCircleFilled, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import styles from './index.less';
import { addParkItem, deletePark, gateAdminItem, getParkTable } from './service';
import { useModel } from 'umi';
import { addListBase, getCity } from './utils';
import RemoteSelect from '@/components/RemoteSelect';
import { ModalForm, ProFormSelect } from '@ant-design/pro-components';

import { getTenantOptions } from '@/pages/Tenant/Tenant/service';

export default () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const tenantId = currUser?.tenantId;
  const actionRef = useRef<ActionType>();

  const [parkId, setParkId] = useState<string>();
  const [addPark, setAddPark] = useState<boolean>(false);
  const [tenant_id, setTenant_id] = useState<string>();
  const ElementComponent = {
    AddElement: (
      <Add
        id={parkId}
        tenant_id={tenant_id}
        isSave={(e) => {
          setIsSave(e);
        }}
        close={() => {
          // eslint-disable-next-line @typescript-eslint/no-use-before-define
          AddClose();
          setIsSave(true);
        }}
      />
    ),
    UpdateElement: (
      <Update
        close={() => {
          // eslint-disable-next-line @typescript-eslint/no-use-before-define
          AddClose();
        }}
        id={parkId}
      />
    ),
    DetailElement: <Detail id={parkId} />,
  };
  const [pageName, setPageName] = useState<string>('停车场列表');
  const [isSave, setIsSave] = useState<boolean>(true);
  const [componentVisibleText, setComponentVisibleText] = useReducer(
    (state: JSX.Element | string, action: string) => {
      switch (action) {
        case 'list':
          window.onbeforeunload = null;
          setPageName('停车场列表');
          return '';
        case 'add':
          setPageName('添加停车场');
          return ElementComponent.AddElement;
        case 'update':
          setPageName('修改停车场');
          return ElementComponent.UpdateElement;
        case 'detail':
          setPageName('停车场详情');
          return ElementComponent.DetailElement;
      }
      return state;
    },
    '',
  );

  const AddClose = () => {
    setComponentVisibleText('list');
  };

  const columns: ProColumns<any>[] = [
    {
      title: '停车场名称',
      dataIndex: 'name',
      hideInForm: true,
      hideInSearch: false,
    },
    {
      title: '停车场位置',
      dataIndex: 'address',
      key: 'addressCode',
      hideInForm: true,
      hideInSearch: true,
      render: (_, record) => {
        return <>{getCity(record.addressCode)}</>;
      },
    },
    {
      title: '收费规则',
      dataIndex: 'schemeName',
      key: 'scheme',
      hideInSearch: true,
    },
    {
      title: '可用车位数',
      dataIndex: 'spaceCount',
      hideInSearch: true,
    },
    {
      title: '剩余车位数',
      dataIndex: 'spaceFreeCount',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: false,
      valueEnum: addListBase.status,
    },
    {
      title: '最近更新时间',
      dataIndex: 'updateTime',
      hideInSearch: true,
    },
    {
      title: '创建人',
      dataIndex: 'creatorName',
      hideInSearch: false,
      renderFormItem: () => (
        <RemoteSelect
          getPopupContainer={(triggerNode) => triggerNode.parentElement} // 保证选择菜单不会随着页面滚动
          fieldNames={{ key: 'key', value: 'id', label: 'name' }}
          request={(search) => gateAdminItem({ name: search! })}
        />
      ),
    },
    {
      fixed: 'right',
      title: '操作',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <>
            {record.status == '1' ? (
              <a
                onClick={() => {
                  setParkId(record.id);
                  setComponentVisibleText('update');
                }}
              >
                编辑车场
              </a>
            ) : (
              <a
                onClick={() => {
                  setParkId(record.id);
                  setComponentVisibleText('add');
                }}
              >
                继续填写
              </a>
            )}
            {record.status == '1' && (
              <>
                <Divider type="vertical" />
                <a
                  onClick={() => {
                    setParkId(record.id);
                    setComponentVisibleText('detail');
                  }}
                >
                  车场详情
                </a>
              </>
            )}
            <Divider type="vertical" />
            <a
              onClick={() => {
                Modal.confirm({
                  title: `确定要删除${record.id}车场吗，?`,
                  icon: <ExclamationCircleFilled />,
                  content: '注意此操作不可逆',
                  okType: 'danger',
                  centered: true,
                  async onOk() {
                    const res = await deletePark(record.id);
                    if (res) {
                      message.success('删除成功');
                      actionRef.current?.reload();
                    }
                  },
                });
              }}
            >
              {record.status == '1' ? '删除' : '撤销新增'}
            </a>
          </>
        );
      },
    },
  ];
  return (
    <PageContainer
      title={
        <div style={{ display: 'flex' }}>
          <Popconfirm
            placement="bottomLeft"
            title={'停车场草稿还未保存，您确定要退出么？'}
            onConfirm={() => {
              setComponentVisibleText('list');
              setIsSave(true);
            }}
            onCancel={() => {}}
            okText="是"
            cancelText="否"
          >
            <Button
              style={{ display: componentVisibleText && !isSave ? 'block' : 'none' }}
              type="link"
            >
              <img
                className={styles.toolBarImg}
                src={'/icons/arrow-return-left.svg'}
                alt="Picture of the author"
                width="21"
                height="21"
              />
            </Button>
          </Popconfirm>
          <Button
            style={{ display: componentVisibleText && isSave ? 'block' : 'none' }}
            type="link"
            onClick={() => {
              setComponentVisibleText('list');
            }}
          >
            <img
              className={styles.toolBarImg}
              src={'/icons/arrow-return-left.svg'}
              alt="Picture of the author"
              width="21"
              height="21"
            />
          </Button>
          {pageName}
        </div>
      }
    >
      {!componentVisibleText && (
        <ProTable<any>
          actionRef={actionRef}
          rowKey="parkinglotId"
          columns={columns}
          scroll={{ x: true }}
          style={{ whiteSpace: 'nowrap' }}
          columnEmptyText="-"
          // headerTitle="角色列表"
          toolBarRender={() => [
            <Button
              key="button"
              icon={<PlusOutlined />}
              type="primary"
              onClick={async () => {
                if (tenantId == '1') {
                  setAddPark(true);
                  return true;
                } else {
                  const res = await addParkItem(tenantId!);
                  if (res && res.data) {
                    setParkId(res.data?.id);
                    setComponentVisibleText('add');
                    setAddPark(false);
                    return true;
                  } else {
                    message.error('车场创建失败，请重试');
                    return false;
                  }
                }
              }}
            >
              添加
            </Button>,
          ]}
          pagination={{
            size: 'default',
            showQuickJumper: true,
            showSizeChanger: true,
            defaultPageSize: 10,
          }}
          request={async (param: any) => {
            const res = await getParkTable(param);
            return { data: res.data?.list, ...res.data };
          }}
        />
      )}
      {componentVisibleText}
      <ModalForm
        title={'管理员创建停车场'}
        width={550}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setAddPark(false);
          },
          centered: true,
          footer: null,
        }}
        open={addPark}
        onFinish={async (value) => {
          const res = await addParkItem(value?.tenant);
          if (res && res.data) {
            setTenant_id(value.tenant);
            setParkId(res.data?.id);
            setComponentVisibleText('add');
            setAddPark(false);
            message.success(`车场创建成功,编号为${res.data?.id}`);
            return true;
          } else {
            message.error('车场创建失败，请重试');
            return false;
          }
        }}
      >
        <ProFormSelect
          label={'所属企业'}
          showSearch
          name="tenant"
          params={{ page: 1, pageSize: 10 }}
          request={async (params, props) => {
            const res: any = await getTenantOptions({
              ...params,
              name: props.text,
            });

            if (res)
              return res.data.map((item: { id: any; name: any }, index: any) => {
                return {
                  value: item.id,
                  label: item.name,
                };
              });
          }}
          rules={[{ required: true, message: '请选择所属企业' }]}
          placeholder="选择所属企业（如未找到目标企业，请先创建企业）"
        />
      </ModalForm>
    </PageContainer>
  );
};
